import { authMiddleware } from '@/lib/api';
import { clientQueryUserDetails, queryPath } from '@/services/api';
import { cookies } from 'next/headers';
import Metadata from '@/lib/metadata';
import UserIdPage from '@/app/[locale]/users/[id]/userid';
import ResetPage from '@/app/[locale]/reset/reset';
import { Metadata as MetadataNext } from 'next';
import type { IUserClientDetails } from '@/interfaces';
import { getMetadata } from '@/lib/tool';
import { notFound } from 'next/navigation';
import UserIdH5Page from '@/app/[locale]/mobile/users/[id]/h5';
import { createTranslator } from 'next-intl';
import { getMessages } from '@/lib/dictionaries';

export async function generateMetadata({
  params: { id, locale },
  searchParams = {},
}: {
  params: { id?: string; locale: string };
  searchParams: {};
}): Promise<MetadataNext> {
  if (!id) {
    notFound();
  }

  const t = createTranslator(await getMessages(locale));

  try {
    const token = authMiddleware(cookies());
    const response = clientQueryUserDetails({
      baseURL: process.env.APP_API_SERVER,
      token,
      id,
      query: searchParams,
    });
    const resp1 = await ((await response) as Response).json();
    const data = resp1.data as IUserClientDetails;

    return getMetadata({
      title: data.user.alias,
      authors: {
        url: `/${data.user.id}`,
        name: data.user.alias,
      },
      creator: `${data.user.alias}(${data.user.id})`,
      description: `${data.user.alias} - ${t('UserIdPage.personalHomepage')}`,
    });
  } catch (e) {
    return getMetadata({ title: t('UserIdPage.userHomepage') });
  }
}

export default async function Page({
  params = {},
  searchParams = {},
}: {
  params: { id?: string };
  searchParams: {
    v?: 'h5';
  };
}) {
  if (!params.id) {
    notFound();
  }

  try {
    const token = authMiddleware(cookies());
    const req1 = queryPath({
      baseURL: process.env.APP_API_SERVER,
      token,
      query: {
        name: '/',
      },
    });
    const req2 = clientQueryUserDetails({
      baseURL: process.env.APP_API_SERVER,
      token,
      id: params.id,
      query: searchParams,
    });

    const responses = await Promise.all([req1, req2]);
    const resp1 = await ((await responses[0]) as Response).json();
    const resp2 = await ((await responses[1]) as Response).json();

    const metadata = new Metadata();
    metadata.set('page', ['/paths', '/'], resp1.data);
    metadata.set(
      'userId',
      ['/users', '/client', params.id, '/details', searchParams, 'infinite'],
      resp2.data,
    );
    return searchParams.v === 'h5' ? (
      <UserIdH5Page metadata={metadata.toString()} />
    ) : (
      <UserIdPage metadata={metadata.toString()} />
    );
  } catch (e) {
    return <ResetPage error={e} />;
  }
}
